# -*- coding: utf-8 -*-
"""
Created on Thu Sep 05 15:11:36 2013

@author: jkwong
"""

#TestSSH.py

import os

import PBAR_HighVoltageCalibrator

# include the final slashes
pathLocal = r'C:\Users\jkwong\Documents\Work\PBAR\data'
pathMar =  r'/home/dastest/vxWorks/data/'
pathAnalysis =  r'/home/dastest/vxWorks/analysis/'


sshObj = PBAR_HighVoltageCalibrator.SecureConnect('pbarsite.no-ip.org', 'dastest', 'School bundle plate chimney 10', 22)
sshObj.ConnectSSHClient()
sshObj.ConnectSFTP()


stdin, stdout, stderr = sshObj.client.exec_command('ls -lt %s*.mar | head -n20' % pathMar)

lines = []
for s in stdout:
    lines.append(s[:-1])
    
# get the latest mar file
# start from most recent file. if not mar file, then skip to next file. if mar file then accept as the latest file
filename = None
fileNumber = None
filePrefix = None
for (index, line) in enumerate(lines):
    # find start index of file name
    if len(line) > 3:
        if line[-3:] == 'mar':
            startIndex = line.find('data/')+5
            filename = line[startIndex:]
            fileNumber = int(filename[2:4])
            filePrefix = filename[0:2]
            break

# Convert to csv if file has been found           
if filename != None:
    # string looks like this: python /home/dastest/vxWorks/analysis/PBAR_Zspec_MarToCSV.py ea 28 28
    command = 'python %sPBAR_Zspec_MarToCSV.py %s %d %d' %(pathAnalysis, filePrefix, fileNumber, fileNumber)
    stdin, stdout, stderr = sshObj.client.exec_command(command)

# grab the csv file
filenameCSV = filename.replace('mar', 'csv')
fullFilenameServer = '%s%s' %(pathAnalysis, filenameCSV)
fullFilenameLocal = os.path.join(pathLocal, filenameCSV)

sshObj.sftp.get(fullFilenameServer, fullFilenameLocal)

# disconnect clients
sshObj.DisconnectSFTP()
sshObj.DisconnectSSHClient()


